package com.kuang.example;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class cookies01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter out = resp.getWriter();

        Cookie[] cookies = req.getCookies();
        if(cookies!=null){
            out.write("你的上次访问时间为：");
            for (int i = 0; i < cookies.length; i++) {
                    Cookie cookie=cookies[i];
                    if("LastloginTime".equals(cookie.getName())){
                        long LastloginTime = Long.parseLong((cookie.getValue()));
                        Date date=new Date(LastloginTime);
                        out.write(date.toLocaleString());
                    }
            }
        }else{
           out.write("你是第一次访问本网站");
        }

        Cookie cookie = new Cookie("LastloginTime", System.currentTimeMillis() + "");
        cookie.setMaxAge(24*60*60);
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
